﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Controls.Input;

namespace Group_Project_Book_Store
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        DatabaseClasses.DatabaseManagment dataManagment = new DatabaseClasses.DatabaseManagment();
        /// <summary>
        /// a list of invoice items
        /// </summary>
        clsInvoiceItems listOfItemsOnInvoice;
        /// <summary>
        /// access the validation class
        /// </summary>
        clsValidation ClassValidation;
        /// <summary>
        /// access the invoice class
        /// </summary>
        clsInvoice NewInvoice;

        //TODO add in total to window
        //TODO labels for Payer Drop down and address box
        //TODO comments
        //TODO try catch for exceptions

        /// <summary>
        /// load main window
        /// </summary>
        public MainWindow()
        {
            Application.Current.ShutdownMode = ShutdownMode.OnMainWindowClose;
            InitializeComponent();
            ClassValidation = new clsValidation();
            NewInvoice = new clsInvoice();
            listOfItemsOnInvoice = new clsInvoiceItems();
            cbCreateNewInvoice_SearchForPayer.ItemsSource = DatabaseClasses.DatabaseManagment.listOfPayers;
            cbCreateNewInvoice_ListOfItems.ItemsSource = DatabaseClasses.DatabaseManagment.listOfBooks;
            lstCreateNewInvoice_ItemsList.Style = clsHelper.GetStyle("List-Grid");
        }

        #region UpdateInputData
        /// <summary>
        /// displays the invoice grid and creates a new list of invoices
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CreateNewInvoiceButton_CallNewInvoiceGrid(object sender, RoutedEventArgs e)
        {
            try
            {
                HideAllGrids();
                grdCreateNewInvoice.Visibility = Visibility.Visible;
                btnDeleteInvoice.IsEnabled = false;
                lblCreateNewInvoice_NewInvoiceNumber.Content = dataManagment.GetNextInvoiceNumber();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// update the payer Address or select a new payer and have the new payer
        /// grid show up
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UpdateNewPayerInformationIntoTheNameAndEnterNewPayerInformation(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                ComboBox cxBox = (ComboBox)sender;
                txInsertNewPayer__PostalCode.ItemsSource = DatabaseClasses.DatabaseManagment.lstPostalCodes;

                if (cxBox.SelectedItem.ToString().Contains("< New Payer >"))
                {
                    grdCreateNewInvoice.Visibility = Visibility.Hidden;
                    grdInsertNewPayer.Visibility = Visibility.Visible;
                    lblCreateNewInvoice_ShowPayerInformation.Content = "";
                }
                else
                {
                    NewInvoice.payer = (clsPayer)cbCreateNewInvoice_SearchForPayer.SelectedItem;
                    lblCreateNewInvoice_ShowPayerInformation.Content = clsPayer.DisplayPayerAddressInformation(NewInvoice.payer);
                }
                ValidateInformationToEnableSaveButton();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// add items to the list of books in a new invoice
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddItemToListofBooksInNewInvoice(object sender, RoutedEventArgs e)
        {
            try
            {
                clsBook book = (clsBook)cbCreateNewInvoice_ListOfItems.SelectedItem;
                book.quantity = book.quantity + 1;

                if (cbCreateNewInvoice_ListOfItems.SelectedItem != null && book != null)
                {
                    lstCreateNewInvoice_ItemsList.ItemsSource = listOfItemsOnInvoice.AddItem(book);
                    lblCreateNewInvoice_TotalOfItems.Content = "Invoice Total : " + clsHelper.ConvertStringToCurreny(NewInvoice.listOfBooksInInvoice.GroupBy(b => b.bookID).Select(b => b.First().bookCost * b.First().quantity).Sum());
                    ValidateInformationToEnableSaveButton();
                    NewInvoice.listOfBooksInInvoice.Add(book);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void DeleteItemToListofBooksInNewInvoice(object sender, RoutedEventArgs e)
        {
            if (lstCreateNewInvoice_ItemsList.SelectedItem != null)
            {
                clsItem item = (clsItem)lstCreateNewInvoice_ItemsList.SelectedItem;
                item.quantity = item.quantity;

                if (lstCreateNewInvoice_ItemsList.SelectedItem != null && item != null && item.book != null)
                {
                    lstCreateNewInvoice_ItemsList.ItemsSource = listOfItemsOnInvoice.RemoveItem(item);
                    ValidateInformationToEnableSaveButton();
                    clsBook book = NewInvoice.listOfBooksInInvoice.Where(b => b.bookID == item.book.bookID).FirstOrDefault();
                    if (book.quantity == 1)
                    {
                        NewInvoice.listOfBooksInInvoice.Remove(book);
                    }
                    else
                    {
                        clsBook updateBook = NewInvoice.listOfBooksInInvoice.Where(b => b.bookID == book.bookID).First();
                        updateBook.quantity = updateBook.quantity - 1;
                    }
                    lblCreateNewInvoice_TotalOfItems.Content = "Invoice Total : " + clsHelper.ConvertStringToCurreny(NewInvoice.listOfBooksInInvoice.GroupBy(b => b.bookID).Select(b => b.First().bookCost * b.First().quantity).Sum());
                } 
            }
        }
        /// <summary>
        /// add the invoice to search grid
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddInvoicesToSearchGrid(object sender, RoutedEventArgs e)
        {
            try
            {
                lstSearchWindow_ListOfInvoicesForDisplay.IsEnabled = false;

                if (cbSearchWindow_InvoiceNumber.SelectedItem != null)
                {
                    int inID = Convert.ToInt32(cbSearchWindow_InvoiceNumber.SelectedItem.ToString());
                    lstSearchWindow_ListOfInvoicesForDisplay.ItemsSource = dataManagment.ListOfIemsByInvoiceID(inID);
                }
                if (cbSearchWindow_InvoiceTotal.SelectedItem != null)
                {
                    int inTotal = clsHelper.ConvertCurrenyToInt(cbSearchWindow_InvoiceTotal.SelectedItem.ToString());
                    lstSearchWindow_ListOfInvoicesForDisplay.ItemsSource = dataManagment.ListOfItemsByTotal(inTotal);
                }
                if (cbSearchWindow_InvoiceBeginDate.SelectedDate != null && cbSearchWindow_InvoiceEndDate.SelectedDate != null)
                {
                    lstSearchWindow_ListOfInvoicesForDisplay.ItemsSource = dataManagment.ListOfItemsByDateRange(cbSearchWindow_InvoiceBeginDate.SelectedDate, cbSearchWindow_InvoiceEndDate.SelectedDate);
                }

                cbSearchWindow_InvoiceTotal.SelectedIndex = -1;
                cbSearchWindow_InvoiceNumber.SelectedIndex = -1;
                cbSearchWindow_InvoiceBeginDate.SelectedDate = null;
                cbSearchWindow_InvoiceEndDate.SelectedDate = null;
                btnSearchWindow_SearchForInvoices.IsEnabled = false;
                lstSearchWindow_ListOfInvoicesForDisplay.IsEnabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        #endregion UpdateInputData

        #region ValidateUserInput
        /// <summary>
        /// Validate user input for number only fields and display invalid image if invalid
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void ValidateNumbersOnly(object sender, KeyEventArgs e)
        {
            try
            {
                TextBox txtBox = (TextBox)sender;
                clsValidation.VerifyOnlyNumeric(InvalidImage, txtBox);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// validates the postal codes
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ValidatePostalCode(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!clsValidation.ValidatePostalCode(txInsertNewPayer__PostalCode.Text))
                {
                    InvalidImage.Visibility = Visibility.Visible;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// validates the information for the save button to be enabled
        /// </summary>
        private void ValidateInformationToEnableSaveButton()
        {
            try
            {
                if (NewInvoice.invoiceDate != null
                    && NewInvoice.invoiceDate > DateTime.Now.AddYears(-100)
                    && NewInvoice.listOfBooksInInvoice.Count() > 0
                    && NewInvoice.payer != null)
                {
                    btnCreateNewInvoice_SaveInvoice.IsEnabled = true;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// checks each key to make sure it is a letter, backspace or delete key
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtInput_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                e.Handled = !IsLetterKey(e.Key) && !IsDelOrBackspaceOrTabKey(e.Key);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// checks each key to make sure it is a Number, backspace or delete key
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtInputforNumbers_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                AutoCompleteBox auto;
                TextBox txt;
                if (sender.GetType().ToString() == "AutoCompleteBox")
                {
                    auto = (AutoCompleteBox)sender;
                    if (IsNumberKey(e.Key) || IsDelOrBackspaceOrTabKey(e.Key))
                    {
                        auto.Tag = true;
                    } 
                }
                else {
                    txt = (TextBox)sender;
                    if (IsNumberKey(e.Key) || IsDelOrBackspaceOrTabKey(e.Key))
                    {
                        txt.Tag = true;
                    } 
                }
                ValidateInformationToEnableSaveButton();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// Checks to see if the key is a letter
        /// </summary>
        /// <param name="inKey"></param>
        /// <returns></returns>
        private bool IsLetterKey(Key inKey)
        {
            try
            {
                if (inKey < Key.D0 || inKey > Key.D9)
                {
                    if (inKey < Key.NumPad0 || inKey > Key.NumPad9)
                    {
                        return true;
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
        }
        /// <summary>
        /// checks to see if the key is a number
        /// </summary>
        /// <param name="inKey"></param>
        /// <returns></returns>
        private bool IsNumberKey(Key inKey)
        {
            try
            {
                //TODO Go over logic 
                if (inKey < Key.D0 || inKey > Key.D9)
                {
                    if (inKey < Key.NumPad0 || inKey > Key.NumPad9)
                    {
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
        }
        /// <summary>
        /// checks to see if the key is delete of tab key
        /// </summary>
        /// <param name="inKey"></param>
        /// <returns></returns>
        private bool IsDelOrBackspaceOrTabKey(Key inKey)
        {
            try
            {
                return inKey == Key.Delete || inKey == Key.Back || inKey == Key.Tab;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
        }

        /// <summary>
        /// Button to cancel the invoice
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancelInvoice_Click(object sender, RoutedEventArgs e)
        {
            //TODO Not sure if this works because of the bug that still comes up when you go back and forth.
            clearInvoiceToCancel();
            HideAllGrids();
        }
        /// <summary>
        /// The New Payer textbox to validate and if not display invalid image
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtInsertNewPayer_Name_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox txtBox = (TextBox)sender;
            clsValidation.ValidateName(txtBox);
            if ((bool)txtBox.Tag)
            {
                DisableInsertNewPayer();
                InvalidImage.Visibility = Visibility.Visible;
            }
        }
        /// <summary>
        /// The New payer email textbox to validate and if not display invalid image
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ValidatePayerEmail(object sender, RoutedEventArgs e)
        {
            clsValidation.ValidateEmail(txtInsertNewPayer__Email);
            if (!(bool)txtInsertNewPayer__Email.Tag)
            {
                InvalidImage.Visibility = Visibility.Visible;
            }
            CheckIfPayerIsValidToSave();
        }
        #endregion ValidateUserInput

        #region UserActionMethodCalls
        /// <summary>
        /// opens the search form window hides the grid and displays the grid design
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OpenSearchForm_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                HideAllGrids();
                grdSearchWindow.Visibility = Visibility.Visible;
                lstSearchWindow_ListOfInvoicesForDisplay.Style = clsHelper.GetStyle("List-Grid-Invoice-Search");
                cbSearchWindow_InvoiceNumber.ItemsSource = DatabaseClasses.DatabaseManagment.listOfInvoices;
                cbSearchWindow_InvoiceTotal.ItemsSource = dataManagment.ListOfTotals();
                lstSearchWindow_ListOfInvoicesForDisplay.ItemsSource = dataManagment.ListOfIemsByInvoiceID();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //TODO Show the Grid for New Items
        /// <summary>
        /// opens the item window and displays the drop down for the item to be added
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OpenItemWindow_Click(object sender, RoutedEventArgs e)
        {

            try
            {
                cbNewItem_UpdateSelectionForNewItem.Items.Clear();
                cbNewItem_UpdateSelectionForNewItem.Items.Add("Book");
                cbNewItem_UpdateSelectionForNewItem.Items.Add("Author");
                cbNewItem_UpdateSelectionForNewItem.Items.Add("Publisher");
                cbNewItem_UpdateSelectionForNewItem.Items.Add("Category");
                cbNewOrModifierNewItem.Items.Clear();
                cbNewOrModifierNewItem.Items.Add("New Item");
                cbNewOrModifierNewItem.Items.Add("Edit or Remove Item");

                HideAllGrids();
                grdMasterNewItem.Visibility = Visibility.Visible;
                //TODO update list of items
                cbEnterNewBook_Author.ItemsSource = DatabaseClasses.DatabaseManagment.listOfAuthors;
                cbEnterNewBook_Publisher.ItemsSource = DatabaseClasses.DatabaseManagment.listOfPublishers;
                cbEnterNewBook_Category.ItemsSource = DatabaseClasses.DatabaseManagment.listOfCategories;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// save the new payer button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveNewPayer(object sender, RoutedEventArgs e)
        {
            try
            {
                //TODO Need to verify information form user or can't save
                NewInvoice.payer.payerName = txtInsertNewPayer_Name.Text;
                NewInvoice.payer.payerAddress = txtInsertNewPayer__Address.Text;
                NewInvoice.payer.payerCity = txtInsertNewPayer__City.Text;
                NewInvoice.payer.payerPostalCode = txInsertNewPayer__PostalCode.Text;
                NewInvoice.payer.payerZIP = txtInsertNewPayer__ZIP.Text;
                NewInvoice.payer.payerPhone = txtInsertNewPayer__Phone.Text;
                NewInvoice.payer.payerEmail = txtInsertNewPayer__Email.Text;

                lblCreateNewInvoice_ShowPayerInformation.Content = clsPayer.DisplayPayerAddressInformation(NewInvoice.payer);
                grdCreateNewInvoice.Visibility = Visibility.Visible;
                grdInsertNewPayer.Visibility = Visibility.Hidden;
                ClearNewItemTextBoxes();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// cancel new payer button and will hide when clicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CancelNewPayer(object sender, RoutedEventArgs e)
        {
            try
            {
                grdCreateNewInvoice.Opacity = 1;
                grdInsertNewPayer.Visibility = Visibility.Hidden;
                
                ClearNewItemTextBoxes();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// save the new category of Publisher, author, category, or book and insert into the database
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveNewCategory(object sender, RoutedEventArgs e)
        {
            try
            {
                switch (cbNewItem_UpdateSelectionForNewItem.SelectedItem.ToString())
                {
                    case "Publisher":
                        clsPublisher NewPublisher = new clsPublisher();
                        NewPublisher.publisherName = txtEnterNewPublisher_PublisherName.Text;
                        dataManagment.InsertNewPublisher(NewPublisher);
                        break;
                    case "Author":
                        clsAuthors NewAuthor = new clsAuthors();
                        NewAuthor.authorFirstName = txtNewAuthor_FirstName.Text;
                        NewAuthor.authorLastName = txtNewAuthor_LastName.Text;
                        dataManagment.InsertNewAuthor(NewAuthor);
                        break;
                    case "Category":
                        clsCategory NewCategory = new clsCategory();
                        NewCategory.categoryName = txtNewCategory_NewCategoryName.Text;
                        NewCategory.categoryDescription = "";
                        dataManagment.InsertNewCategory(NewCategory);
                        break;
                    case "Book":
                        if ((bool)txtEnterNewBook_Cost.Tag && (bool)cbEnterNewBook_Publisher.Tag && (bool)cbEnterNewBook_Category.Tag)
                        {
                            clsBook NewBook = new clsBook();
                            NewBook.bookTitle = txtEnterNewBook_BookTitle.Text;
                            NewBook.ISBN = txtEnterNewBook_ISBN.Text;
                            NewBook.bookCost = Convert.ToInt32(txtEnterNewBook_Cost.Text);
                            NewBook.Publisher = (clsPublisher)cbEnterNewBook_Publisher.SelectedItem;
                            NewBook.Author = (clsAuthors)cbEnterNewBook_Author.SelectedItem;
                            NewBook.categoryType = (clsCategory)cbEnterNewBook_Category.SelectedItem;
                            if (wpEnterNewBook.Tag == null)
                            {
                                dataManagment.InsertNewBook(NewBook);
                            }
                            else
                            {
                                clsBook bk = (clsBook)txtEnterNewBook_BookTitle.Tag;
                                NewBook.bookID = bk.bookID;
                                dataManagment.UpdateBook(NewBook);
                            }
                        }
                        break;
                }
                
                HideAllGrids();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// cancel the new category and set the text to blank
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CancelNewCategory(object sender, RoutedEventArgs e)
        {
            try
            {
                HideAllGrids();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void ClearNewItemTextBoxes()
        {
            txtEnterNewPublisher_PublisherName.Text = "";
            txtNewAuthor_FirstName.Text = "";
            txtNewAuthor_LastName.Text = "";
            txtNewCategory_NewCategoryName.Text = "";
            txtEnterNewBook_BookTitle.Text = "";
            wpEnterNewBook.Tag = null;
            txtEnterNewBook_ISBN.Text = "";
            txtEnterNewBook_Cost.Text = "";
            cbEnterNewBook_Publisher.SelectedItem = "";
            cbEnterNewBook_Author.SelectedItem = "";
            cbEnterNewBook_Category.SelectedItem = "";
            cbNewItem_UpdateSelectionForNewItem.SelectedIndex = -1;
            cbNewOrModifierNewItem.SelectedIndex = -1;
            txtInsertNewPayer_Name.Tag = false;
            txtInsertNewPayer__Address.Tag = false;
            txtInsertNewPayer__City.Tag = false;
            txInsertNewPayer__PostalCode.Tag = false;
            txtInsertNewPayer__ZIP.Tag = false;
            txtInsertNewPayer__Phone.Tag = false;
            txtInsertNewPayer__Email.Tag = false;
            txtInsertNewPayer_Name.Text = "";
            txtInsertNewPayer__Address.Text = "";
            txtInsertNewPayer__City.Text = "";
            txInsertNewPayer__PostalCode.Text = "";
            txtInsertNewPayer__ZIP.Text = "";
            txtInsertNewPayer__Phone.Text = "";
            txtInsertNewPayer__Email.Text = "";
        }
        /// <summary>
        /// Update the panel from the user selection
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UpdateNewItemPanelFromUserSelection(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                ComboBox cbBox = (ComboBox)sender;

                if (cbBox.SelectedItem != null)
                {
                    string selection = cbBox.SelectedItem.ToString();
                    wpNewAuthor.Visibility = Visibility.Hidden;
                    wpEnterNewBook.Visibility = Visibility.Hidden;
                    wpEnterNewPublisher.Visibility = Visibility.Hidden;
                    wpNewCategory.Visibility = Visibility.Hidden;

                    switch (selection)
                    {
                        case "Author":
                            wpNewAuthor.Visibility = Visibility.Visible;
                            break;
                        case "Book":
                            wpEnterNewBook.Visibility = Visibility.Visible;
                            break;
                        case "Publisher":
                            wpEnterNewPublisher.Visibility = Visibility.Visible;
                            break;
                        case "Category":
                            wpNewCategory.Visibility = Visibility.Visible;
                            break;
                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// button save invoice
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSaveInvoice_Click(object sender, RoutedEventArgs e)
        {
            if (NewInvoice.invoiceID == 0)
            {
                dataManagment.InsertNewInvoice(NewInvoice);
            }
            else
            {
                dataManagment.UpdateInvoice(NewInvoice);
                btnEditInvoice.IsEnabled = false;
                btnDeleteInvoice.IsEnabled = false;
                btnCreateNewInvoice_SaveInvoice.IsEnabled = false;
            }

            clearInvoiceToCancel();
            HideAllGrids();
        }

        #endregion UserActionMethodCalls

        #region UpdateVisibilityOfSection
        /// <summary>
        /// Method to Hide all the Grides from the main windwo
        /// </summary>
        private void HideAllGrids()
        {
            try
            {
                ClearNewItemTextBoxes();
                grdCreateNewInvoice.Visibility = Visibility.Hidden;
                grdInsertNewPayer.Visibility = Visibility.Hidden;
                grdSearchWindow.Visibility = Visibility.Hidden;
                grdNewItem.Visibility = Visibility.Hidden;
                wpEnterNewBook.Visibility = Visibility.Hidden;
                wpEnterNewPublisher.Visibility = Visibility.Hidden;
                wpNewAuthor.Visibility = Visibility.Hidden;
                wpNewCategory.Visibility = Visibility.Hidden;
                grdMasterNewItem.Visibility = Visibility.Hidden;

            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// Method to Display the new payer that is inserted
        /// </summary>
        private void DisableInsertNewPayer()
        {
            try
            {
                txtInsertNewPayer_Name.IsEnabled = false;
                txtInsertNewPayer__Address.IsEnabled = false;
                txtInsertNewPayer__City.IsEnabled = false;
                txInsertNewPayer__PostalCode.IsEnabled = false;
                txtInsertNewPayer__ZIP.IsEnabled = false;
                txtInsertNewPayer__Phone.IsEnabled = false;
                txtInsertNewPayer__Email.IsEnabled = false;
                btnInsertNewPayer_Cancel.IsEnabled = false;
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message); 
            }
        }
        /// <summary>
        /// Method to Enable information to insert new payer
        /// </summary>
        private void EnableInsertNewPayer()
        {
            try
            {

                txtInsertNewPayer_Name.IsEnabled = true;
                txtInsertNewPayer__Address.IsEnabled = true;
                txtInsertNewPayer__City.IsEnabled = true;
                txInsertNewPayer__PostalCode.IsEnabled = true;
                txtInsertNewPayer__ZIP.IsEnabled = true;
                txtInsertNewPayer__Phone.IsEnabled = true;
                txtInsertNewPayer__Email.IsEnabled = true;
                btnInsertNewPayer_Cancel.IsEnabled = true;

            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// Method to clear the invoice when canceled
        /// </summary>
        private void clearInvoiceToCancel()
        {
            try
            {
                lblCreateNewInvoice_ShowPayerInformation.Content = "";
                lstCreateNewInvoice_ItemsList.ItemsSource = new List<int>();
                dpCreateNewInvoice_NewInvoiceDate.SelectedDate = null;
                cbCreateNewInvoice_ListOfItems.Text = "";
                cbCreateNewInvoice_SearchForPayer.SelectedIndex = -1;
            }
            catch (NullReferenceException)
            {
                //Do nothing
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
        /// <summary>
        /// Method to hide the invalid image
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HideInvalidImage(object sender, MouseButtonEventArgs e)
        {
            try
            {
                InvalidImage.Visibility = Visibility.Hidden;
                EnableInsertNewPayer();
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

        #endregion UpdateVisibilityOfSection
        /// <summary>
        /// enables the search button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void EnableSearchButton(object sender, SelectionChangedEventArgs e)
        {
            try
            {

                btnSearchWindow_SearchForInvoices.IsEnabled = true;
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// add the dte to the new invoice
        /// calls the validate to enable save button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddDateToNewInvoice(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (dpCreateNewInvoice_NewInvoiceDate.SelectedDate != null)
                {
                    NewInvoice.invoiceDate = (DateTime)dpCreateNewInvoice_NewInvoiceDate.SelectedDate;
                    ValidateInformationToEnableSaveButton();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

            }
        }
        /// <summary>
        /// edit invoice button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void EditInvoiceButton(object sender, RoutedEventArgs e)
        {
            try
            {
                lblCreateNewInvoice_ShowPayerInformation.Content = clsPayer.DisplayPayerAddressInformation(NewInvoice.payer);
                dpCreateNewInvoice_NewInvoiceDate.SelectedDate = NewInvoice.invoiceDate;
                lblCreateNewInvoice_NewInvoiceNumber.Content = NewInvoice.invoiceID.ToString();
                foreach (var book in NewInvoice.listOfBooksInInvoice)
                {
                    for (int i = 0; i < book.quantity; i++)
                    {
                        lstCreateNewInvoice_ItemsList.ItemsSource = listOfItemsOnInvoice.AddItem(book);
                    }
                }
                lblCreateNewInvoice_TotalOfItems.Content = "Invoice Total : " + clsHelper.ConvertStringToCurreny(NewInvoice.listOfBooksInInvoice.GroupBy(b => b.bookID).Select(b => b.First().bookCost * b.First().quantity).Sum());
                HideAllGrids();
                grdCreateNewInvoice.Visibility = Visibility.Visible;
                btnEditInvoice.IsEnabled = false;
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);

            }
        }
        /// <summary>
        /// add the item that was selected to the new invoice
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddSearchItemSelectionToNewInvoice(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (lstSearchWindow_ListOfInvoicesForDisplay.SelectedItem != null)
                {
                    clsItem selectedItem = (clsItem)lstSearchWindow_ListOfInvoicesForDisplay.SelectedItem;
                    NewInvoice = selectedItem.invoice;
                    btnEditInvoice.IsEnabled = true;
                    btnDeleteInvoice.IsEnabled = true;
                }
                else
                {
                    btnEditInvoice.IsEnabled = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// Button that deletes the invoice
        /// Hides the grids
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeleteInvoiceButton(object sender, RoutedEventArgs e)
        {
            try
            {
                dataManagment.DeleteInvoice(NewInvoice);
                btnDeleteInvoice.IsEnabled = false;
                HideAllGrids();
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
        private void ValidateNewPayerInformation(object sender, RoutedEventArgs e)
        {
            TextBox txtBox = (TextBox)sender;
            clsValidation.ValidateName(txtBox);
            CheckIfPayerIsValidToSave();
        }
        private void CheckIfPayerIsValidToSave()
        {
            if ((bool)txtInsertNewPayer_Name.Tag && (bool)txtInsertNewPayer__Address.Tag && (bool)txtInsertNewPayer__City.Tag && (bool)txInsertNewPayer__PostalCode.Tag && (bool)txtInsertNewPayer__ZIP.Tag && (bool)txtInsertNewPayer__Phone.Tag && (bool)txtInsertNewPayer__Email.Tag)
            {
                btnInsertNewPayer_Save.IsEnabled = true;
                DisableInsertNewPayer();
            } 
        }
        private void UpdateViewForItemUpdateOrDelete(object sender, SelectionChangedEventArgs e)
        {
                ComboBox cbBox = (ComboBox)sender;

                grdNewItem.Visibility = Visibility.Hidden;
                grdEditOrUpdateItem.Visibility = Visibility.Hidden;

                if (cbBox.SelectedItem != null)
                {
                    string selection = cbBox.SelectedItem.ToString();
                    switch (selection)
                    {
                        case "New Item":
                            grdNewItem.Visibility = Visibility.Visible;
                            break;
                        case "Edit or Remove Item":
                            grdEditOrUpdateItem.Visibility = Visibility.Visible;
                            lstItems_ItemsList.ItemsSource = DatabaseClasses.DatabaseManagment.listOfBooks;
                            break;
                        default:
                            break;
                    }
                }
        }

        private void VerifyValueIsInList(object sender, RoutedEventArgs e)
        {
            AutoCompleteBox auto = (AutoCompleteBox)sender;

            switch (auto.Name)
            {
                case "txInsertNewPayer__PostalCode":
                    auto.Tag = DatabaseClasses.DatabaseManagment.lstPostalCodes.Contains(auto.Text);
                    break;
                case "cbEnterNewBook_Publisher":
                    auto.Tag = DatabaseClasses.DatabaseManagment.listOfPublishers.Select(p => p.publisherName).Contains(auto.Text);
                    break;
                case "cbEnterNewBook_Author":
                    auto.Tag = DatabaseClasses.DatabaseManagment.listOfAuthors.Select(a => a.authorLastName + ", " + a.authorFirstName).Contains(auto.Text);
                    break;
                case "cbEnterNewBook_Category":
                    auto.Tag = DatabaseClasses.DatabaseManagment.lstPostalCodes.Contains(auto.Text);
                    break;
                default:
                    break;
            }
            CheckIfPayerIsValidToSave();
        }

        private void EnableUpdateAndDeleteButtons(object sender, SelectionChangedEventArgs e)
        {
            if (lstItems_ItemsList.SelectedItem != null)
            {
                btnDeleteItem.IsEnabled = true;
                btnUpdateItem.IsEnabled = true;
            }
            else
            {
                btnDeleteItem.IsEnabled = false;
                btnUpdateItem.IsEnabled = false;
            }
        }
        private void UpdateTheSelectedItem(object sender, RoutedEventArgs e)
        {
            clsBook book = (clsBook)lstItems_ItemsList.SelectedItem;
            txtEnterNewBook_BookTitle.Text = book.bookTitle;
            wpEnterNewBook.Tag = book;
            txtEnterNewBook_ISBN.Text = book.ISBN;
            txtEnterNewBook_Cost.Text = book.bookCost.ToString();
            cbEnterNewBook_Publisher.SelectedItem = book.Publisher;
            cbEnterNewBook_Author.SelectedItem = book.Author;
            cbEnterNewBook_Category.SelectedItem = book.categoryType;

            wpEnterNewPublisher.Visibility = Visibility.Hidden;
            wpNewAuthor.Visibility = Visibility.Hidden;
            wpNewCategory.Visibility = Visibility.Hidden;
            grdEditOrUpdateItem.Visibility = Visibility.Hidden;

            grdMasterNewItem.Visibility = Visibility.Visible;
            grdNewItem.Visibility = Visibility.Visible;
            wpEnterNewBook.Visibility = Visibility.Visible;

            //cbNewOrModifierNewItem.SelectedIndex = -1;
            cbNewItem_UpdateSelectionForNewItem.SelectedValue = "Book";
        }
        private void DeleteTheSeletedItem(object sender, RoutedEventArgs e)
        {
            clsBook book = (clsBook)lstItems_ItemsList.SelectedItem;
            List<int> total = (from invoice in DatabaseClasses.DatabaseManagment.listOfInvoices from bks in invoice.listOfBooksInInvoice where bks.bookID == book.bookID  select invoice.invoiceID).ToList();
            if (total.Any())
            {
                string listofin = "";
                foreach (int b in total.ToList())
                {
                    listofin = listofin + b + ", ";
                }
                MessageBox.Show("Can Not Remove Selection as it is currently used in " + listofin);
            } else 
            {
                dataManagment.DeleteBook(book);
                lstItems_ItemsList.ItemsSource = DatabaseClasses.DatabaseManagment.listOfBooks;
            }
        }

    }
}
